import AStar from "../Astar/Astar";

const { ccclass, property } = cc._decorator;

@ccclass
export default class DijkstraPlayer extends cc.Component {
    private _path: cc.Vec2[];
    private _moveTarget: any;
    private _speed: any;

    onTouchEnd(e: cc.Event.EventTouch) {
        this._speed = null;
        let startX = this.node.x + this.node.parent.x;
        let startY = this.node.y + this.node.parent.y;
        startX = Math.floor(startX / window["Game"].itemWH)
        startY = Math.floor(startY / window["Game"].itemWH)
        let endPos = e.getLocation();
        let endX = Math.floor(endPos.x / window["Game"].itemWH)
        let endY = Math.floor(endPos.y / window["Game"].itemWH)
        // console.time("1")
        // AStar.instance.pushFindPathCommand(startX, startY, endX, endY, this.node.uuid, (path) => {
        //     this._path = path;
        //     if (this._path) {
        //         this.nextTarget();
        //     }
        // });
        // console.timeEnd("1")

    }

    nextTarget() {
        this._moveTarget = null;
        this._speed = null;
        if (this._path && this._path.length > 0) {
            this._moveTarget = this._path.shift();
            let nowPos = this.node.getPosition();
            let dir = this._moveTarget.sub(nowPos);
            this._speed = dir.normalize().mul(500);
        }
    }

    update(dt) {
        if (this._speed) {
            let dis = this._speed.mul(dt);
            let disLen = dis.len();
            let nowPos = this.node.getPosition();
            let sub = this._moveTarget.sub(nowPos);
            let subLen = sub.len();
            if (disLen >= subLen) {
                disLen = subLen;
                this.node.setPosition(this._moveTarget);
                this.nextTarget();
            } else {
                this.node.setPosition(nowPos.add(dis));
            }
        }
    }
}